package ru.stepanovdn.trading.server.service.dictionary

import org.springframework.retry.annotation.Retryable
import org.springframework.stereotype.Service
import ru.stepanovdn.trading.server.service.tinkoff.ITinkoffCommonAPI

import jakarta.annotation.PostConstruct
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import ru.tinkoff.piapi.contract.v1.*

@Service
class InstrumentService (
    @Autowired val tinkoffCommonAPI: ITinkoffCommonAPI
){
    private val log = LoggerFactory.getLogger(javaClass)
    private var instrumentByFigi: MutableMap<String, Instrument>? = null

    class Instrument (
        var figi: String? = null,
        var currency: String? = null,
        var name: String? = null,
        var lot: Int = 0
    )

    fun getInstrument(figi: String): Instrument? {
        val instrument = instrumentByFigi!![figi]
        if (instrument == null) {
            log.warn("Instrument not found: {}", figi)
        }
        return instrument
    }

    @PostConstruct
    @Retryable
    private fun init() {
        // load all instruments to memory
        instrumentByFigi = HashMap()

        val shares: MutableList<Share> = tinkoffCommonAPI!!.api!!.instrumentsService.allSharesSync
        shares.forEach { i -> instrumentByFigi!![i.figi] = Instrument(i.figi, i.currency, i.name, i.lot) }

        val futures: MutableList<Future> = tinkoffCommonAPI.api!!.instrumentsService.allFuturesSync
        futures.forEach { i -> instrumentByFigi!![i.figi] = Instrument(i.figi, i.currency, i.name, i.lot) }

        val bounds: MutableList<Bond> = tinkoffCommonAPI.api!!.instrumentsService.allBondsSync
        bounds.forEach { i -> instrumentByFigi!![i.figi] = Instrument(i.figi, i.currency, i.name, i.lot) }

        val etfs: MutableList<Etf> = tinkoffCommonAPI.api!!.instrumentsService.allEtfsSync
        etfs.forEach { i -> instrumentByFigi!![i.figi] = Instrument(i.figi, i.currency, i.name, i.lot) }

        val currencies: MutableList<Currency> = tinkoffCommonAPI.api!!.instrumentsService.allCurrenciesSync
        currencies.forEach { i ->
            instrumentByFigi!![i.figi] = Instrument(i.figi, i.currency, i.name, i.lot)
        }
    }
}
